<template>
  <div class="message-item ai-message" :class="{ streaming: message.isStreaming }">
    <MessageHeader role-label="AI助手" :timestamp="message.timestamp" />

    <div class="message-content">
      <div class="message-text" v-html="formattedContent"></div>

      <TTSControls 
        :enabled="ttsEnabled" 
        :is-playing="isPlaying" 
        :show-voice-selector="showVoiceSelector"
        :audio-url="message.audioUrl"
        :has-content="!!message.content"
        :current-voice="selectedVoice"
        @play="onPlay"
        @stop="onStop"
        @voice-change="handleVoiceChange"
      />

      <div class="streaming-indicator" v-if="message.isStreaming">
        <div class="typing-dots">
          <span></span>
          <span></span>
          <span></span>
        </div>
      </div>
    </div>
  </div>
  
</template>

<script setup>
import { computed, ref } from 'vue'
import MarkdownService from '@/services/MarkdownService.js'
import ttsService from '@/services/TTSService.js'
import MessageHeader from '@/components/MessageItem/components/MessageHeader.vue'
import TTSControls from '@/components/MessageItem/components/TTSControls.vue'

const props = defineProps({
  message: { type: Object, required: true },
  isPlaying: { type: Boolean, default: false },
  ttsEnabled: { type: Boolean, default: true },
  showVoiceSelector: { type: Boolean, default: true }
})

const emit = defineEmits(['play-tts', 'stop-tts', 'update-audio-url'])

const selectedVoice = ref(ttsService.getCurrentVoice())

const formattedContent = computed(() => {
  if (!props.message || !props.message.content) return ''
  const content = typeof props.message.content === 'string' ? props.message.content : String(props.message.content)
  try {
    // 若检测到 Markdown，使用渲染；否则保持原 HTML 或换行处理
    if (MarkdownService.hasMarkdown(content)) {
      return MarkdownService.render(content)
    }
    return content.replace(/\n/g, '<br>')
  } catch (error) {
    console.error('AI内容渲染失败:', error)
    return String(content).replace(/\n/g, '<br>')
  }
})

const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
}

const onPlay = async (done) => {
  if (!props.ttsEnabled) { done && done(); return }
  try {
    if (!props.message.audioUrl) {
      await generateTTS()
    }
    emit('play-tts', props.message.id)
  } catch (e) {
    console.error('AI TTS generation failed:', e)
  } finally {
    done && done()
  }
}

const onStop = () => {
  emit('stop-tts')
}

const generateTTS = async () => {
  const plainText = MarkdownService.getPlainText(props.message.content)
  const audioUrl = await ttsService.generateAudio(plainText, props.message.id, selectedVoice.value)
  emit('update-audio-url', props.message.id, audioUrl)
}

const handleVoiceChange = (voiceId) => {
  selectedVoice.value = voiceId
  ttsService.setVoice(voiceId)
  if (props.message.audioUrl) {
    props.message.audioUrl = null
    generateTTS()
  }
}

</script>

<style scoped>
@import './index.css';
</style>


